<?php
/**
 * 喂食系统
 * @author: lizhi <lizhi7@xin.com>
 * Date: 2018/4/3 17:43
 */

namespace app\controllers;
use app\models\Feed;
use app\models\UserPet;
use Yii;
use yii\web\Controller;
class FeedController extends Controller
{

    /**
     * @author lizhi7  <lizhi7@xin.com>
     * @return \yii\web\Response
     */
    public function actionAdd()
    {
        if (Yii::$app->user->isGuest) {
            return $this->asJson(['code' => 10001, 'msg' => '未登录']);
        }
        $userId = Yii::$app->user->identity->getId();
        $amount = Yii::$app->request->post('amount');
        $pid = Yii::$app->request->post('pid');
        $Feed = new Feed();
        if($amount <= 0) {
            return $this->asJson(['code' => 10002, 'msg' => '喂食金额必须大于0']);
        }
        $feedSum = $Feed->getTodaySumFeed($pid);
        if($feedSum + $amount > Feed::MAX_FEED) {
            return $this->asJson(['code' => 10003, 'msg' => '喂食已满']);
        }
        $data = $Feed->addFeed($userId, $pid, $amount);
        if (!empty($data)) {
            if($feedSum + $amount == Feed::MAX_FEED) {
                $userPet = new UserPet();
                $userPetRow = $userPet->find()->where('user_id=:user_id and pid=:pid and ascription_status=1',
                    [':user_id' => $userId, ':pid' => $pid]);
                $userPetRow->feed_status = 1;
                $userPetRow->updted_at = time();
                $userPetRow->save();
            }
        }
        return $this->asJson(['code' => 10000, 'msg' => '喂食成功', 'data' => $data]);
    }
}